package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingProjectDto;
import com.zzyl.entity.NursingProject;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.service.NursingProjectService;
import com.zzyl.vo.NursingProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author lsq
 */
@Service
public class NursingProjectServiceImpl implements NursingProjectService {
    @Autowired
    private NursingProjectMapper nursingProjectMapper;
    @Override
    public PageResponse<NursingProjectVo> getByPage(String name, Integer status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<NursingProjectVo> nursingProjects = nursingProjectMapper.selectByPage(name, status);
        return PageResponse.of(nursingProjects, NursingProjectVo.class);
    }

    @Override
    public void add(NursingProjectDto nursingProjectDto) {
        NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
        Integer count =  nursingProjectMapper.getNursingProjectByName(nursingProject.getName());
        //重复抛异常
        if (count>0){
            throw new BaseException(BasicEnum.NURSING_PROJECT_EXISTED);
        }
        //不重复新增
        nursingProjectMapper.add(nursingProject);
    }

    @Override
    public NursingProjectVo getById(Long id) {

        return nursingProjectMapper.selectById(id);
    }

    @Override
    public void update(NursingProjectDto nursingProjectDto) {
        NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
        nursingProject.setUpdateTime(LocalDateTime.now());
        nursingProject.setCreateBy(1L);
        nursingProjectMapper.update(nursingProject);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        nursingProjectMapper.updateStatus(id,status);
    }

    @Override
    public void delete(Long id) {
        NursingProject nursingProject = nursingProjectMapper.getById(id);
        if (nursingProject==null){
            throw new BaseException(BasicEnum.NURSING_PROJECT_IS_USED);
        }
        if (nursingProject.getStatus()==1){
            throw new BaseException(BasicEnum.NURSING_PROJECT_NOT_EXISTED);
        }

        nursingProjectMapper.delete(id);
    }

    /**
     * 查询所有护理项目
     * @return
     */
    @Override
    public List<NursingProjectVo> getAll() {
        return nursingProjectMapper.getAll();
    }
}


